<?php

namespace app\util;

require_once 'alipay/aop/AopClient.php';
require_once 'alipay/aop/request/AlipayTradeAppPayRequest.php';
require_once 'alipay/aop/request/AlipayTradeQueryRequest.php';
require_once 'alipay/aop/request/AlipayTradeRefundRequest.php';
require_once 'alipay/aop/request/AlipayTradeFastpayRefundQueryRequest.php';

/*
 * 支付宝支付
 */

class Alipay
{
    //*****
    //APP支付参数
    //*****

    //网关
    const GATEWAY_URL = 'https://openapi.alipay.com/gateway.do';

    //appId
    const APP_ID = '2016032801248475';

    //开发者私钥
    const RSA_PRIVATE_KEY = 'MIIEpAIBAAKCAQEAuqOKI5k5jU7RoT5bkCZshWvGJ/N3qSj81fYafZhVufWfPswCsDMwYsFcHUwpqjEUpg/zUW0kmlgxcxFcH65G9ZdMEoL5tVGYsd7tnhGhvgfKrrNpDDevFD1h+2iDsRDQY8G/Y+n2SbkKkrANG5NvnTR8Z311MKRfTcag7pQQFavb7t+TevyDhHJ/UMMJmasUKopzgtUquCHHMbzq3wGuHMXIg2O+C41FGoj1SCT2nummo2uWFvo2J8RiQJbNYVWo4/yVotVFuOCvwM3PQP3VINIB7Yd/Xa33Tqs6ei4EDQEO/xDgoDvVn5PihlvLXu7Z+rBrPYGaOU0dE46iSZIJTQIDAQABAoIBAQC5hQYzDIPgqpBFry5kw0zr8o0t+Rzg0RVBuTfr0BimmDiKu0+QxdE62OkvVh20RsU3rHM4ZT0VDsVYk9D2zM1MIfBEFl0QluMpK2cW0H/t3ODjdwLcWh12CO30cZc10njSMCyGrHFcJssTtFvTJWK06Q8f790lVL5HGUGu5Q53+oI0EsexjWubmWAb6EOhMC8sTqd7yqteSl4maZ2DsMFizaugoHt8POA2WG94bvjl11LLZVfu/4PuwyLA20GsVuMgWgMlGO/zadC/AQTw6EejQlqD47Q3zBJe8dTwbnzRGAsvmqv+SDRoYOnFvR9eRdhGtM+WTxucZsOZ2rUBYmMhAoGBAN1sVgsVaaqZ7zJool0oQBIBlknWaQmzFRVWALUxSRbX5zCLWZ2v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wBejJxt4MzjaDQcBC/dhqIswSEJ8kbZupiIMC3Ci1pCgpIma3kyO2rjaH5E2D6ffZL3rCJDYse9PuevcMMqkK9GaQSp/1A2wx2E5o/wYLsTD4+6FWNAGSfJKjvZHSRXegfLP5+jymLTeOyVwj+wx/oUwKwgp8iDFA6cikRQ2Zv+L3iZwIDAQAB';

    //回调地址
    const NOTIFY_URL = 'http://app.dwkkm.com/kkmtest/public/index/pay/alipaynotify';
    
    //回调地址（优享）
    const USHARE_NOTIFY_URL = 'http://app.dwkkm.com/kkmtest/public/index/pay/usharealipaynotify';


    //*****
    //网页支付参数
    //*****

    //网关
    const HTML_GATEWAY_URL = 'https://openapi.alipay.com/gateway.do';

    //appId
    const HTML_APP_ID = '2017122701271123';

    //开发者私钥
    const HTML_RSA_PRIVATE_KEY = 'MIIEowIBAAKCAQEAug+wedajZwBGkOMeiMWQC5xJe1Ur0Qm+TGewosWmwLkZr1VcrnaObEL6FwNX9aFfvTu5zQQ2BT7zlCAodrlt25Ikand+ayHP6P9/5P5fL9vqE9gcpHotqz4XjBcB4e/sNXqi48pBpN0uGLrzGIud1AzncRLacZxWyrvPKUo9usX2FboFgGR1Y3u/lBK+cugZ2G+w3Y37lHV+aaY4pTOgNF4O/zd/Lkik32WmQr+tUq8Iy9MGu8jMlfo8Dpyi+xuP5Xe0S6DmmiNw0dqCCjJra3WzhGU5BhSr1MykH5uaTOWNRaVU4yq+TI68O0pRKwYcZ65fyKPrk4Z6Uapu+cM5AwIDAQABAoIBADEClvrRBgPIt83MdauTVskoJtb87WjHxz+7BHUr2Svk1hYwRxSRmBx+XAAZ2l6SXnSrOdr+I/inx2OaQO5dE8oFqd/9j+hKZMi8HIVGV+50YClQAON2Z3c3CN7W5KEOIMtJfYTBLx9tP4o2HHi3tiA4MfLAA5hvlREb/YqjyrTao2LwvvnrID850PQdmVYWLeyR2I/WaHd7w+L1ChaQ0edX7X/Z8QSfqyJVLbsA2UXoXV655UB1FthGVtPpmo2pOPU/rlJdGc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NzzvFrnCdeTdtltkCH6SOrGG5BntYqI6bnOwsv0DqlcGfA4YYvWjZ0UWj4KzUDwW3WEWJh/dKvT5a83gAPzd8TazMPxuxDN3JmSb7pVEe3vxHDY9DUU6F/gJxcvjAjU5BxgQ5wBejJxt4MzjaDQcBC/dhqIswSEJ8kbZupiIMC3Ci1pCgpIma3kyO2rjaH5E2D6ffZL3rCJDYse9PuevcMMqkK9GaQSp/1A2wx2E5o/wYLsTD4+6FWNAGSfJKjvZHSRXegfLP5+jymLTeOyVwj+wx/oUwKwgp8iDFA6cikRQ2Zv+L3iZwIDAQAB';

    /*
     * 支付宝支付
     */
    public static function doPay($body, $subject, $out_trade_no, $total_amount, $params = [])
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APP_ID;
        $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey = self::ALIPAYRSA_PUBLIC_KEY;
        $aop->format = "json";
        $aop->postCharset = "UTF-8";
        $aop->signType = "RSA2";

        $request = new \AlipayTradeAppPayRequest();

        /*
        $bizcontent = "{\"body\":\"我是测试数据\","
            . "\"subject\": \"App支付测试\","
            . "\"out_trade_no\": \"20170125test01\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        */

        if (count($params) > 0) {
            //限时抢购设置交易起始时间和交易结束时间
            $timeout_express = $params['timeout_express'];
            $bizcontent = '{"body":"' . $body . '","subject":"' . $subject . '","out_trade_no":"' . $out_trade_no . '","total_amount":"' . $total_amount . '","product_code":"QUICK_MSECURITY_PAY","timeout_express":"' . $timeout_express . '"}';
        } else {
            $bizcontent = '{"body":"' . $body . '","subject":"' . $subject . '","out_trade_no":"' . $out_trade_no . '","total_amount":"' . $total_amount . '","product_code":"QUICK_MSECURITY_PAY"}';
        }

        $request->setNotifyUrl(self::NOTIFY_URL);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);

        return htmlspecialchars($response);
    }
    
    /*
     * 支付宝支付(优享)
     */
    public static function usharedoPay($body, $subject, $out_trade_no, $total_amount, $params = [])
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APP_ID;
        $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey = self::ALIPAYRSA_PUBLIC_KEY;
        $aop->format = "json";
        $aop->postCharset = "UTF-8";
        $aop->signType = "RSA2";

        $request = new \AlipayTradeAppPayRequest();

        /*
        $bizcontent = "{\"body\":\"我是测试数据\","
            . "\"subject\": \"App支付测试\","
            . "\"out_trade_no\": \"20170125test01\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        */

        if (count($params) > 0) {
            //限时抢购设置交易起始时间和交易结束时间
            $timeout_express = $params['timeout_express'];
            $bizcontent = '{"body":"' . $body . '","subject":"' . $subject . '","out_trade_no":"' . $out_trade_no . '","total_amount":"' . $total_amount . '","product_code":"QUICK_MSECURITY_PAY","timeout_express":"' . $timeout_express . '"}';
        } else {
            $bizcontent = '{"body":"' . $body . '","subject":"' . $subject . '","out_trade_no":"' . $out_trade_no . '","total_amount":"' . $total_amount . '","product_code":"QUICK_MSECURITY_PAY"}';
        }

        $request->setNotifyUrl(self::USHARE_NOTIFY_URL);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);

        return htmlspecialchars($response);
    }

    /*
     * 支付宝查询订单
     */
    public static function doQuery($out_trade_no)
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APP_ID;
        $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey = self::ALIPAYRSA_PUBLIC_KEY;
        $aop->format = 'json';
        $aop->postCharset = 'UTF-8';
        $aop->signType = 'RSA2';

        $request = new \AlipayTradeQueryRequest();

        /*
        $request->setBizContent("{" .
            "\"out_trade_no\":\"20150320010101001\"," .
            "\"trade_no\":\"2014112611001004680 073956707\"" .
            "  }");
        */

        $bizcontent = '{"out_trade_no":"' . $out_trade_no . '","trade_no":""}';

        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        return $result->$responseNode;
    }

    /*
     * 网页支付宝查询订单
     * 和 支付宝查询订单(doQuery) 查询结果一样
     */
    public static function htmlDoQuery($out_trade_no)
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = self::HTML_GATEWAY_URL;
        $aop->appId = self::HTML_APP_ID;
        $aop->rsaPrivateKey = self::HTML_RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey = self::HTML_ALIPAYRSA_PUBLIC_KEY;
        $aop->format = 'json';
        $aop->postCharset = 'UTF-8';
        $aop->signType = 'RSA2';

        $request = new \AlipayTradeQueryRequest();

        /*
        $request->setBizContent("{" .
            "\"out_trade_no\":\"20150320010101001\"," .
            "\"trade_no\":\"2014112611001004680 073956707\"" .
            "  }");
        */

        $bizcontent = '{"out_trade_no":"' . $out_trade_no . '","trade_no":""}';

        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        return $result->$responseNode;
    }

    /*
     * 支付宝退款
     */
    public function refund($out_trade_no,$refund_amount){
        $out_request_no=$out_trade_no;
        $aop = new \AopClient();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APP_ID;
        $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey=self::ALIPAYRSA_PUBLIC_KEY;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest();
        $bizcontent = '{"out_trade_no":"'.$out_trade_no.'","refund_amount":"'.$refund_amount.'","out_request_no":"'.$out_request_no.'"}';
        $request->setBizContent($bizcontent);
        $result = $aop->execute ( $request); 

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return [
                    'code' => 0,
                    'data' => '成功',
                ];
        } else {
           return [
                    'code' => 1,
                    'data' => $result->$responseNode,
                ];
        }
    }
    
    /*
     * 支付宝退款查询
     */
    public function findrefund($out_trade_no){
        $out_request_no=$out_trade_no;
        $aop = new \AopClient ();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APP_ID;
        $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;
        $aop->alipayrsaPublicKey=self::ALIPAYRSA_PUBLIC_KEY;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeFastpayRefundQueryRequest ();
        $bizcontent = '{"out_trade_no":"'.$out_trade_no.'","out_request_no":"'.$out_request_no.'"}';
        $request->setBizContent($bizcontent);
        
        $result = $aop->execute ( $request); 

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){//成功
            return [
                    'code' => 0,
                    'data' => $result->$responseNode,
                ];
        } else {
            return [
                    'code' => 1,
                    'data' => $result->$responseNode,
                ];
        }
    }

}